<template>
	<view class="profile-page">
		<!-- 顶部导航 -->
		<u-navbar 
			:title="'个人信息'" 
			:leftIcon="'arrow-left'" 
			:bgColor="'#FF5033'"
			:titleStyle="{ color: '#fff', fontSize: '32rpx', fontWeight: '500' }"
			:leftIconColor="'#fff'"
			:leftIconSize="'24'"
			@leftClick="goBack"
			:safeAreaInsetTop="true"
			:placeholder="true"
		>
			<template #right>
				<view class="navbar-right" @click="toggleEdit">
					<text class="edit-btn">{{ isEditing ? '完成' : '编辑' }}</text>
				</view>
			</template>
		</u-navbar>

		<!-- 个人信息内容 -->
		<view class="wrapper">
			<!-- 头像 -->
			<view class="user-icon display-flex">
				<view class="label">
					<text>头像</text>
				</view>
				<view class="avatar-container" @click="handleAvatarClick">
					<image :src="userInfo.avatar || serverAddress+'img/icon-mrtx@3x.png'" class="avatar-img"
						mode="aspectFill" />
				</view>
			</view>

			<!-- 昵称 -->
			<view class="personal-item display-flex">
				<view class="label">
					<text>昵称</text>
				</view>
				<view class="input-container">
					<input v-model="userInfo.nickname" type="text" maxlength="16" :readonly="!isEditing"
						class="text-input" placeholder="请输入昵称" />
				</view>
			</view>

			<!-- 性别 -->
			<view class="personal-item display-flex">
				<view class="label">
					<text>性别</text>
				</view>
				<view class="gender-container">
					<view v-for="(gender, index) in genderOptions" :key="index" class="gender-item"
						@click="selectGender(gender.value)">
						<image
							:src="userInfo.sex === gender.value ? serverAddress+'img/radio-checked.png' : serverAddress+'img/radio.png'"
							class="radio-icon" mode="aspectFit" />
						<text>{{ gender.label }}</text>
					</view>
				</view>
			</view>

			<!-- 登录手机号 -->
			<view class="personal-item display-flex">
				<view class="label">
					<text>登录手机号</text>
				</view>
				<view class="phone-container">
					<text class="phone-text">{{ userInfo.phone }}</text>
				</view>
			</view>

			<!-- 邀请二维码 -->
			<view class="personal-item display-flex" @click="goInviteQrcode">
				<view class="label">
					<text>邀请二维码</text>
				</view>
				<view class="arrow-container">
					<image :src="serverAddress+'img/icon-Get-into@3x.png'" class="arrow-icon" mode="aspectFit" />
				</view>
			</view>

			<!-- 出生日期 -->
			<view class="personal-item display-flex">
				<view class="label">
					<text>出生日期</text>
				</view>
				<view class="date-container">
					<picker mode="date" :value="userInfo.birthday" :start="'1950-01-01'" :end="maxDate"
						@change="onDateChange" :disabled="!isEditing">
						<view class="picker-content">
							<text class="date-text">{{ userInfo.birthday || '请选择您的出生日期' }}</text>
							<image :src="serverAddress+'img/icon-Get-into@3x.png'" class="arrow-icon" mode="aspectFit" />
						</view>
					</picker>
				</view>
			</view>

			<!-- 账户归属地 -->
			<view class="personal-item display-flex">
				<view class="label">
					<text>账户归属地</text>
				</view>
				<view class="address-container">
					<text class="address-text">{{ userInfo.address }}</text>
				</view>
			</view>
		</view>

		<!-- 选择图像弹窗 -->
		<view v-if="showImageModal" class="choose-icon mask-click" >
			<view class="modal-content" @click.stop>
				<view class="modal-item" @click="chooseImage">选择图像</view>
				<view class="modal-item" @click="hideImageModal">取消</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		profileApi
	} from '@/api/index.js'
	import {
		inject
	} from 'vue'
	export default {
		data() {
			return {
				serverAddress: inject('$serverAddress'),
				isEditing: false,
				showImageModal: false,

				// 用户信息
				userInfo: {
					avatar: '',
					nickname: '',
					sex: 0, // 0:保密 1:男 2:女
					birthday: '',
					phone: '',
					address: ''
				},

				// 性别选项
				genderOptions: [{
						label: '男',
						value: 1
					},
					{
						label: '女',
						value: 2
					},
					{
						label: '保密',
						value: 0
					}
				],

				personalIcon: '' // 个人头像临时存储
			}
		},
		computed: {
			// 最大日期（16岁以上）
			maxDate() {
				const today = new Date()
				const maxYear = today.getFullYear() - 16
				return `${maxYear}-12-31`
			}
		},
		onLoad() {
			this.loadUserInfo()
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 加载用户详细信息
			async loadUserInfo() {
				try {
					uni.showLoading({
						title: '加载中...'
					})
					const res = await profileApi.getUserDetail()
					if (res.r === 0) {
						const data = res.data

						// 处理头像路径
						let iconPath = ''
						if (data.file_path) {
							iconPath = data.file_path.indexOf('http') !== -1 ? data.file_path :
								`https://static.youpin91.com/${data.file_path}`
							this.personalIcon = iconPath
						} else {
							iconPath = '/static/img/icon-mrtx@3x.png'
							this.personalIcon = ''
						}

						this.userInfo = {
							avatar: iconPath,
							nickname: data.nickname || '',
							sex: data.sex || 0,
							birthday: data.birthday || '',
							phone: data.phone || '',
							address: data.address || ''
						}
					} else {
						uni.showToast({
							title: res.msg || '获取用户信息失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取用户信息失败:', error)
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 切换编辑状态
			async toggleEdit() {
				if (this.isEditing) {
					// 完成编辑，提交修改
					await this.updateUserInfo()
				} else {
					// 开始编辑
					this.isEditing = true
				}
			},

			// 更新用户信息
			async updateUserInfo() {
				// 验证昵称
				if (!this.userInfo.nickname.trim()) {
					uni.showToast({
						title: '昵称不可为空',
						icon: 'none'
					})
					return
				}
				if (this.userInfo.nickname.length < 2) {
					uni.showToast({
						title: '昵称不能少于2位',
						icon: 'none'
					})
					return
				}
				if (this.userInfo.nickname.length > 16) {
					uni.showToast({
						title: '昵称不能大于16位',
						icon: 'none'
					})
					return
				}

				try {
					uni.showLoading({
						title: '保存中...'
					})

					// 处理图片路径
					let filePath = this.personalIcon
					if (filePath && filePath.indexOf('http') !== -1) {
						filePath = filePath.slice(filePath.indexOf('img'))
					}

					const res = await profileApi.updateUserDetail({
						nickname: this.userInfo.nickname.trim(),
						sex: this.userInfo.sex,
						birthday: this.userInfo.birthday,
						file_path: filePath
					})

					if (res.r === 0) {
						this.isEditing = false
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: res.msg || '保存失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('更新用户信息失败:', error)
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 处理头像点击
			handleAvatarClick() {
				if (this.isEditing) {
					this.showImageModal = true
				}
			},

			// 选择图片
			chooseImage() {
				this.hideImageModal()
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						this.uploadImage(tempFilePath)
					}
				})
			},

			// 上传图片
			async uploadImage(filePath) {
				try {
					uni.showLoading({
						title: '上传中...'
					})
					const res = await profileApi.uploadImage(filePath)
					if (res.r === 0 && res.data.file_path && res.data.file_path.length > 0) {
						const url = res.data.file_path[0]
						this.personalIcon = url
						this.userInfo.avatar = `https://static.youpin91.com/${url}`
						// 自动触发保存
						await this.updateUserInfo()
					} else {
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('上传图片失败:', error)
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 隐藏图片选择弹窗
			hideImageModal() {
				this.showImageModal = false
			},

			// 选择性别
			selectGender(value) {
				if (this.isEditing) {
					this.userInfo.sex = value
				}
			},

			// 日期改变
			onDateChange(e) {
				this.userInfo.birthday = e.detail.value
			},

			// 跳转到邀请二维码页面
			goInviteQrcode() {
				uni.navigateTo({
					url: '/pages/invite/qrcode'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.profile-page {
		background-color: #f7f7f7;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	// 顶部导航右侧
	.navbar-right {
		padding: 10rpx;

		.edit-btn {
			font-size: 30rpx;
			color: #fff;
		}
	}

	// 内容区域
	.wrapper {
		background-color: white;
		font-size: 56rpx;
		padding-top: 40rpx;
		flex: 1;
	}

	// 通用显示弹性布局
	.display-flex {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	// 头像区域
	.user-icon {
		margin-left: 60rpx;
		margin-right: 60rpx;
		border-bottom: 1rpx solid #e8e8e8;
		position: relative;

		.label {
			font-size: 32rpx;
			color: #333;
		}

		.avatar-container {
			position: relative;

			.avatar-img {
				height: 84rpx;
				width: 84rpx;
				border-radius: 20rpx;
				object-fit: cover;
			}
		}
	}

	// 个人信息项
	.personal-item {
		height: 92rpx;
		margin-left: 60rpx;
		margin-right: 60rpx;
		position: relative;
		line-height: 92rpx;
		border-bottom: 1rpx solid #e8e8e8;

		.label {
			font-size: 32rpx;
			color: #333;
		}

		.input-container {
			flex: 1;
			margin-left: 60rpx;

			.text-input {
				width: 100%;
				height: 80rpx;
				font-size: 28rpx;
				color: #4b4b4b;
				text-align: right;
				border: none;
				outline: none;
				background: transparent;
			}
		}

		.gender-container {
			display: flex;
			align-items: center;
			gap: 60rpx;

			.gender-item {
				height: 100%;
				font-size: 28rpx;
				color: #333;
				display: flex;
				align-items: center;
				gap: 12rpx;

				.radio-icon {
					width: 33rpx;
					height: 33rpx;
				}
			}
		}

		.phone-container {
			.phone-text {
				font-size: 28rpx;
				color: #333;
			}
		}

		.date-container {
			.picker-content {
				display: flex;
				align-items: center;
				gap: 20rpx;
			}

			.date-text {
				font-size: 28rpx;
				color: #333;
			}
		}

		.arrow-container {
			display: flex;
			align-items: center;
		}

		.arrow-icon {
			width: 24rpx;
			height: 48rpx;
		}

		.address-container {
			.address-text {
				font-size: 28rpx;
				color: #333;
			}
		}
	}

	// 选择图像弹窗
	.choose-icon {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 9999;
		display: flex;
		align-items: flex-end;
		justify-content: center;

		.modal-content {
			width: 100%;
			background-color: #fff;
			border-radius: 24rpx 24rpx 0 0;
			padding: 40rpx;

			.modal-item {
				height: 100rpx;
				line-height: 100rpx;
				text-align: center;
				font-size: 32rpx;
				color: #333;
				border-bottom: 1rpx solid #f0f0f0;

				&:last-child {
					border-bottom: none;
					color: #999;
				}

				&:active {
					background-color: #f5f5f5;
				}
			}
		}
	}

	// 屏幕遮罩
	.mask-click {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 9998;
	}

	// 必填标识
	.required {
		color: #FF2E00;
		margin-right: 20rpx;
	}

	// 字体颜色
	.fontco {
		color: #8D8D8D;
	}
</style>